package omm.dao.imp;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import omm.dao.UserDAO;
import omm.domain.Branch;
import omm.domain.ConnectionManager;
import omm.domain.Entity;
import omm.domain.User;
import omm.domain.exceptions.DatabaseException;
import omm.domain.exceptions.UserCannotLoginException;
import omm.domain.exceptions.UserWrongPasswordException;

@Repository
public class DatabaseUserDAO implements UserDAO {

	private ConnectionManager manager;

	@Autowired
	public DatabaseUserDAO(ConnectionManager manager) {
		this.manager = manager;
	}

	@Override
	public User authenticate(User user) {
		Connection conn = manager.getConnection();
		//TODO: Hacer conexion a la base con spring
		PreparedStatement stmt = null;
		ResultSet result = null;

		try {
			// TODO: Ver si hay que validar el parametro ingresado
			String sql = "select * from usuario where username = ?";
			stmt = conn.prepareStatement(sql);
			stmt.setString(1, user.getUsername());
			result = stmt.executeQuery();

		} catch (Exception e) {
			manager.closeConnection(conn);
			throw new DatabaseException(e);
		}

		try {

			if (result.next()) {

				String pass = result.getString("password_md5");
				if ( pass.equals( user.getPasswordMD5())) {
					user.setId(result.getInt("id"));
					user.setName(result.getString("nombre"));
					user.setLastname(result.getString("apellido"));

					user.setPage(result.getString("homepage"));
					user.setMail(result.getString("email"));
					user.setFlags(result.getInt("flags"));

					// TODO: Armar objetos
					user.setEntity(new Entity());
					user.setBranch(new Branch());
					// user.setBoss(result.getString("nombre"));

					manager.closeConnection(conn);
					return user;
				}

			}

			throw new UserWrongPasswordException();

		} catch (SQLException e) {
			throw new UserCannotLoginException(e);
		}
	}
}
